package com.lxm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lxm.common.contants.AddressConstants;
import com.lxm.common.tools.UserHolder;
import com.lxm.dto.AddressDTO;
import com.lxm.dto.Result;
import com.lxm.entity.Address;
import com.lxm.mapper.AddressDao;
import com.lxm.service.AddressService;
import com.lxm.vo.AddressVO;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 地址表 服务实现类
 * </p>
 *
 * @author ${author}
 * @since 2024-10-02
 */
@Service
public class AddressServiceImpl extends ServiceImpl<AddressDao, Address> implements AddressService {

    /**
     * 添加地址
     *
     * @param addressDTO
     * @return
     */
    @Override
    public Result add(AddressDTO addressDTO) {
        // 获取当前用户id
        Long userId = UserHolder.getUser().getUserId();
        Address address = BeanUtil.toBean(addressDTO, Address.class);
        // 设置用户id
        address.setUserId(userId);
        boolean isSuccess = save(address);
        return isSuccess ? Result.ok(AddressConstants.ADD_ADDRESS_SUCCESS)
                : Result.fail(AddressConstants.ADD_ADDRESS_FAIL);
    }

    /**
     * 更新地址
     *
     * @param addressDTO
     * @return
     */

    @Override
    public Result updateAddress(AddressDTO addressDTO) {
        // 获取当前用户id
        Long userId = UserHolder.getUser().getUserId();
        Address address = BeanUtil.toBean(addressDTO, Address.class);
        boolean isSuccess = update(address, new LambdaQueryWrapper<Address>()
                .eq(Address::getUserId, userId));
        return isSuccess ? Result.ok(AddressConstants.UPDATE_ADDRESS_SUCCESS)
                : Result.fail(AddressConstants.UPDATE_ADDRESS_FAIL);
    }

    /**
     * 查询用户地址列表
     *
     * @return
     */

    @Override
    public Result listByUserId() {
        // 获取当前用户id
        Long userId = UserHolder.getUser().getUserId();
        // 查询地址列表
        List<Address> addressList = lambdaQuery()
                .eq(Address::getUserId, userId)
                .select(Address::getAddressId, Address::getProvince,
                        Address::getCity, Address::getDetail, Address::getIsActive)
                .list();
        // 封装为addressVO并且返回
        return Result.ok(BeanUtil.copyToList(addressList, AddressVO.class));
    }

    @Override
    public Result deleteAddress(Long id) {
        Long userId = UserHolder.getUser().getUserId();
        boolean isSuccess = remove(new LambdaQueryWrapper<Address>()
                .eq(Address::getAddressId, id)
                .eq(Address::getUserId, userId));
        return isSuccess ? Result.ok(AddressConstants.DELETE_ADDRESS_SUCCESS)
                : Result.fail(AddressConstants.DELETE_ADDRESS_FAIL);
    }


}
